#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2006 Pierpaolo FOllia <pfollia@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.

import rhythmdb, rb
import dbus

VERSION = '0.1'
STATUS_MESSAGE = '♫ #title by #artist'

class EresevaStatus(rb.Plugin):

    def __init__(self):
        rb.Plugin.__init__(self)
        self.last_status_message = ''
        self.original_status_message = 'hacking on ereseva dbus'

    def activate(self, shell):
        self.sp = shell.get_player ()
        self.db = shell.get_property('db')
        self.is_playing = self.sp.get_playing()

        #Connect to "play song" event playing-changed
        self.pc_id = self.sp.connect('playing-changed', self.playing_changed)
        self.psc_id = self.sp.connect('playing-song-changed', self.playing_entry_changed)

        try:
            self.ereseva_interface = dbus.Interface(\
                    dbus.SessionBus().get_object(\
                            'org.tapioca.Ereseva', '/org/tapioca/Ereseva'\
                    ), 'org.tapioca.Ereseva'
            )
        except:
            print 'Ereseva not running. Plugin disabled'

        #Change the message if there is something playing now...
        self.playing_entry_changed (self.sp, self.sp.get_playing_entry ())

    def deactivate(self, shell):
        if self.ereseva_interface is not None:
            self.ereseva_interface.SetPresenceCustomMessage(self.original_status_message)
        self.sp.disconnect (self.psc_id)
        self.sp.disconnect (self.pc_id)

    def playing_changed(self, sp, entry):
        if self.ereseva_interface is not None:
            status = self.last_status_message
            if self.sp.get_playing() == False:
                status = status + ' [paused]'
            self.ereseva_interface.SetPresenceCustomMessage(status)

        self.is_playing = self.sp.get_playing()

    def playing_entry_changed(self, sp, entry):
        if self.ereseva_interface is not None:
            self.last_entry = entry
            self.change_status_message()

    def change_status_message(self):
        if self.last_entry is not None:
            artist = self.db.entry_get(self.last_entry, rhythmdb.PROP_ARTIST)
            title = self.db.entry_get(self.last_entry, rhythmdb.PROP_TITLE)

            status = STATUS_MESSAGE
            if artist is not None:
                status = status.replace('#artist', artist)
            if title is not None:
                status = status.replace('#title', title)

            if self.sp.get_playing() == False:
                status = status + ' [paused]'

            self.last_status_message = status
            self.ereseva_interface.SetPresenceCustomMessage(status)
        else:
            self.ereseva_interface.SetPresenceCustomMessage(self.original_status_message)

